package com.huaxin.hxcloud.frendcircles;

import android.content.Context;
import android.view.View;
import android.widget.Toast;

import com.huaxin.common.Entity.FrendCircleBean;
import com.huaxin.common.Entity.UserDTO;
import com.huaxin.common.Global;
import com.huaxin.common.frendcircle.bean.CommentItem;
import com.huaxin.common.frendcircle.bean.User;
import com.huaxin.common.frendcircle.listener.IDataRequestListener;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 */
public class CirclePresenter implements CircleContract.Presenter {
    private CircleModel circleModel;
    private CircleContract.View view;
    private Context context;

    public static User curUser;

    private static int circleId = 0;
    private static int commentId = 0;

    public CirclePresenter(CircleContract.View view, Context context) {
        circleModel = new CircleModel(context);
        this.view = view;
        this.context = context;
        getCurUser();
    }

    public void getCurUser() {
        UserDTO user = Global.user;
        curUser = new User("" + user.getUserId(), user.getNickName(), user.getImgUrl());
    }

    public void loadData(final int loadType, int questionId) {
        requestDatas(loadType, questionId);
    }

    private static List<CommentItem> createCommentItemList(FrendCircleBean.CommentArrayBean commentArrayBean) {
        List<CommentItem> items = new ArrayList<CommentItem>();
        if (commentArrayBean != null) {
            List<FrendCircleBean.CommentArrayBean.ChildCommentArrayBean> childCommentArray = commentArrayBean.getChildCommentArray();
            for (int i = 0; i < childCommentArray.size(); i++) {
                FrendCircleBean.CommentArrayBean.ChildCommentArrayBean childCommentArrayBean = childCommentArray.get(i);
                CommentItem item = new CommentItem();
                item.setContent(childCommentArrayBean.getContent());
                FrendCircleBean.CommentArrayBean.ChildCommentArrayBean.FromPeopleBean fromPeople = childCommentArrayBean.getFromPeople();
                item.setUser(new User("" + fromPeople.getId(), fromPeople.getNickName(), fromPeople.getImg()));
                FrendCircleBean.CommentArrayBean.ChildCommentArrayBean.ToPeopleBean toPeople = childCommentArrayBean.getToPeople();
                item.setToReplyUser(new User("" + toPeople.getId(), toPeople.getNickName(), toPeople.getImg()));
                item.setId(String.valueOf(commentId++));//
                item.setParentId(childCommentArrayBean.getId());
                item.setIsResponse(childCommentArrayBean.getIsResponse());
                items.add(item);
            }
        }
        return items;
    }

    private void requestDatas(final int loadType, int questionId) {
        Call<FrendCircleBean> baseDTOCall = RequestHelper.getRequestApi().requestFrendDatas(questionId);
        baseDTOCall.enqueue(new Callback<FrendCircleBean>() {
            @Override
            public void onResponse(Call<FrendCircleBean> call, Response<FrendCircleBean> response) {
                if (response.isSuccessful()) {
                    FrendCircleBean body = response.body();
                    List<FrendCircleBean.CommentArrayBean> commentArray = body.getCommentArray();
                    List<CircleItem> datas = new ArrayList<CircleItem>();
                    for (int i = 0; i < commentArray.size(); i++) {
                        CircleItem item = new CircleItem();
                        FrendCircleBean.CommentArrayBean commentArrayBean = commentArray.get(i);
                        FrendCircleBean.CommentArrayBean.PublisherBean publisher = commentArrayBean.getPublisher();
                        User user = new User("" + publisher.getId(), publisher.getNickName(), publisher.getImg());
                        item.setUser(user);
                        item.setContent(commentArrayBean.getContent());
                        item.setCreateTime(StringUtils.friendlyTime(new Date(commentArrayBean.getPublishDate())));
                        item.setComments(createCommentItemList(commentArrayBean));
                        item.setId(String.valueOf(circleId++));//
                        item.setParentId(commentArrayBean.getId());
                        item.setLike(commentArrayBean.isLike());
                        datas.add(item);
                    }

                    if (view != null) {
                        //数据回调的接口
                        view.update2loadData(loadType, datas);
                    }
                } else {
                    Toast.makeText(context, "数据异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<FrendCircleBean> call, Throwable t) {
                Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * @Title: deleteCircle
     * @Description: 删除动态
     */
    public void deleteCircle(final String circleId) {
        circleModel.deleteCircle(new IDataRequestListener() {

            @Override
            public void loadSuccess(Object object) {
                if (view != null) {
                    view.update2DeleteCircle(circleId);
                }
            }
        });
    }


    /**
     * @Title: addComment
     * @Description: 增加评论
     */
    public void addComment(final String content, final CommentConfig config) {
        if (config == null) {
            return;
        }
        circleModel.addComment(new IDataRequestListener() {
            @Override
            public void loadSuccess(Object object) {
                CommentItem newItem = null;
                if (config.commentType == CommentConfig.Type.PUBLIC) {
                    newItem = createPublicComment(content);
                } else if (config.commentType == CommentConfig.Type.REPLY) {
                    newItem = createReplyComment(config.replyUser, content);
                }
                if (view != null) {
                    view.update2AddComment(config.circlePosition, newItem);
                }
            }
        });
    }

    private static CommentItem createPublicComment(String content) {
        CommentItem item = new CommentItem();
        item.setId(String.valueOf(commentId++));
        item.setContent(content);
        item.setUser(curUser);
        item.setIsResponse(0);
        return item;
    }

    private static CommentItem createReplyComment(User replyUser, String content) {
        CommentItem item = new CommentItem();
        item.setId(String.valueOf(commentId++));
        item.setContent(content);
        item.setUser(curUser);
        item.setToReplyUser(replyUser);
        item.setIsResponse(1);
        return item;
    }

    /**
     * @Title: deleteComment
     * @Description: 删除评论
     */
    public void deleteComment(final int circlePosition, final String commentId) {
        circleModel.deleteComment(new IDataRequestListener() {

            @Override
            public void loadSuccess(Object object) {
                if (view != null) {
                    view.update2DeleteComment(circlePosition, commentId);
                }
            }

        });
    }

    /**
     * @param commentConfig
     */
    public void showEditTextBody(CommentConfig commentConfig) {
        if (view != null) {
            view.updateEditTextBodyVisible(View.VISIBLE, commentConfig);
        }
    }


    /**
     * 清除对外部对象的引用，反正内存泄露。
     */
    public void recycle() {
        this.view = null;
    }
}
